package com.share.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.common.core.exception.ServiceException;
import com.share.user.domain.UserInfo;
import com.share.user.mapper.IUserInfoMapper;
import com.share.user.service.IUserInfoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
@Slf4j
public class IUserInfoServiceImpl extends ServiceImpl<IUserInfoMapper,UserInfo> implements IUserInfoService {

    @Autowired
    private IUserInfoMapper iUserInfoMapper;
    @Autowired
    private final WxMaService wxMaService;
    @Override
    public UserInfo wxLogin(String code) {
        String openId =null;
        try {
            //获取openId
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            openId = sessionInfo.getOpenid();
            log.info("【小程序授权】openId={}", openId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("微信登录失败");
        }
        //根据openId查询用户信息
        UserInfo userInfo = this.getOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openId));
        if (null == userInfo) {
            //如果是第一次登录就添加用户信息到数据库
            userInfo = new UserInfo();
            userInfo.setNickname(String.valueOf(System.currentTimeMillis()));
            userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            userInfo.setWxOpenId(openId);
            this.save(userInfo);
        }
        return userInfo;
    }



    @Override
    public Boolean updateUserLogin(UserInfo updateUserLogin) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(updateUserLogin.getId());
        userInfo.setLastLoginIp(updateUserLogin.getLastLoginIp());
        userInfo.setLastLoginTime(updateUserLogin.getLastLoginTime());
        iUserInfoMapper.updateById(userInfo);
//        //登录日志
//        UserLoginLog userLoginLog = new UserLoginLog();
//        userLoginLog.setUserId(userInfo.getId());
//        userLoginLog.setMsg("小程序登录");
//        userLoginLog.setIpaddr(updateUserLogin.getLastLoginIp());
//        userLoginLogMapper.insert(userLoginLog);
        return true;
    }




}
